﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Data;
using System.ServiceModel.Description;
using System.Xml.Linq;
using System.Xml;
using System.Net;
using System.Xml.XPath;
using Evb.Security.Credentials;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Text.RegularExpressions;


namespace KOPLibrary.SharePointManagement
{
    public class SharePointManager
    {
        public string ProcessException { get; set; }
        public string[] taskcolumns = new string[] { "ows_AssignedTo", "ows_Title", "ows_Created", "ows_StartDate", "ows_Modified", "ows_DueDate", "ows_Status", "ows_TaskStatus"  };


        public static XElement GetXElement(XmlNode xmlnode)
        {
            XDocument doc = new XDocument();
            using (XmlWriter xmlWriter = doc.CreateWriter())
                xmlnode.WriteTo(xmlWriter);
            return doc.Root;
        }


        private TaskData GetWorkflowData(XmlNode tempnode)
        {
            string[] data = new string[taskcolumns.Length];
            int temp;
            for (int i = 0; i < taskcolumns.Length; i++)
            {
                data[i] = (tempnode.Attributes[taskcolumns[i]] == null) ? string.Empty : tempnode.Attributes[taskcolumns[i]].Value;
                if (i == 0)
                {
                    temp = data[i].IndexOf("#");
                    if (temp != -1) data[i] = data[i].Remove(0, temp + 1);
                }
                if (i == 2)
                {
                    temp = data[i].IndexOf("+");
                    if (temp != -1) data[i] = data[i].Remove(temp, data[i].Length - temp).Replace("T", " ");
                }
            }
            TaskData td = new TaskData(data);
            return td;
        }


        private string GetServerWebServiceUrl(string url)
        {
            string serviceaddress = url;
            Regex rex = new Regex("http://[A-Za-z0-9-:.]+/");
            Match mc = rex.Match(url);
            if (string.IsNullOrEmpty(mc.Value)) return null;
            return mc.Value + "/_vti_bin/webs.asmx";
        }

        public TaskDataList GetTaskData(string documenturl, SPConnectionSettings settings)
        {
            TaskDataList wflist = null;
            XmlNode ws = null;
            SpWebService.Workflow client;
            SpWebServiceForWebUrl.Webs webs;
            string temp;
            try
            {
                temp = GetServerWebServiceUrl(documenturl);
                if (temp == null)
                {
                    ProcessException = "İş akışını görmek istediğiniz döküman sharepoint üzerinden açılmalıdır";
                    return null;
                }
                webs = new SpWebServiceForWebUrl.Webs();
                webs.Url = temp;
                if (settings != null)
                {
                    webs.UseDefaultCredentials = false;
                    webs.Credentials = new NetworkCredential(settings.Username, settings.Password);
                }
                else
                {
                    webs.UseDefaultCredentials = true;
                }
                string weburl = webs.WebUrlFromPageUrl(documenturl);
                client = new SpWebService.Workflow();
                client.Url = weburl+"/_vti_bin/workflow.asmx";           
                documenturl = documenturl.Replace(" ", "%20");
                if (settings != null)
                {
                    client.UseDefaultCredentials = false;
                    client.Credentials = new NetworkCredential(settings.Username, settings.Password);                       
                }
                else
                {
                    client.UseDefaultCredentials = true;                    
                }                
                ws = client.GetWorkflowDataForItem(documenturl);
            }
            catch (System.Net.WebException ee)
            {
                if (ee.Message.ToString().IndexOf("401") != -1)
                {
                    using (CredentialPromptDialog dlg = new CredentialPromptDialog())
                    {
                        dlg.TargetName = "temp";
                        if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            IntPtr ptr = Marshal.SecureStringToBSTR(dlg.Password);
                            string username = dlg.UserName.Remove(0, 5);
                            string pass = Marshal.PtrToStringUni(ptr);
                            return GetTaskData(documenturl, new SPConnectionSettings(username, pass));
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                ProcessException = ee.Message.ToString();
                return null;
            }
            wflist = new TaskDataList();
            XmlNode tempnode;
            try
            {
                if ((((ws.FirstChild).ChildNodes[0]).ChildNodes[0]).ChildNodes.Count < 1)
                {
                    ProcessException = "Geçerli döküman için iş akışı bulunamadı";
                    return null;
                }
            }
            catch
            {
                ProcessException = "Geçerli döküman için iş akışı bulunamadı";
                return null;
            }
            for (int i = 0; i < (((ws.FirstChild).ChildNodes[0]).ChildNodes[0]).ChildNodes.Count; i++)
            {
                tempnode = ((((ws.FirstChild).ChildNodes[0]).ChildNodes[0]).ChildNodes[i]);
                wflist.Add(GetWorkflowData(tempnode));
            }
            return wflist;
        }


    }
}
